package system;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * This class implements a session of Chat.
 * 
 * @author Alexandre, Cristovao, Raul, Rodolpho, Tales
 * 
 */
public class Chat {

	private int portChat;
	private String user1;
	private String user2;
	private List<String> msgs;

	private final String LINE_SEPARATOR = System.getProperty("line.separator");

	/**
	 * Constructor.
	 */
	public Chat() {
		portChat = 0;
		user1 = "";
		user2 = "";
		msgs = new ArrayList<String>();
	}

	/**
	 * Set a port for the current session of chat
	 * 
	 * @param port
	 */
	public void setPortChat(int port) {
		this.portChat = port;
	}

	/**
	 * Returns port of current chat session
	 * @return portChat
	 */
	public int getPortChat() {
		return portChat;
	}

	/**
	 * Initialize a chat between two users.
	 * 
	 * @param user1
	 * @param user2
	 */
	public void initChat(String user1, String user2) {
		this.setUser1(user1);
		this.setUser2(user2);
	}

	/**
	 * Set the user 1 of current session chat.
	 * 
	 * @param user
	 */
	private void setUser1(String user) {
		this.user1 = user;
	}

	/**
	 * Set the user 2 of current session chat
	 * 
	 * @param user
	 */
	private void setUser2(String user) {
		this.user2 = user;
	}

	/**
	 * Send a message to other user.
	 * 
	 * @param to
	 *            - user who will receive the message
	 * @param message
	 */
	public void sendMessage(String to, String message) {
		msgs.add(((to.equalsIgnoreCase(user1)) ? user2 : user1) + ": " + message);
	}

	/**
	 * Receive a message from other user of session chat.
	 * 
	 * @param from
	 *            - who send a message
	 * @return getMessages - the sent message
	 */
	public String getMessage(String from) {
		String saida = msgs.get(msgs.size() - 1);
		saida = saida.substring(0, saida.indexOf(": "));
		return saida;
	}

	/**
	 * Create log file of chat.
	 */
	public void createLogFile() {
		String nomeDoArquivo = "";
		if (user1.compareTo(user2) > 0) {
			nomeDoArquivo = user2 + "-" + user1;
		} else {
			nomeDoArquivo = user1 + "-" + user2;
		}

		try {

			FileWriter file = new FileWriter(new File(nomeDoArquivo + ".log"),
					true);
			for (String daVez : msgs) {
				file.write(daVez + LINE_SEPARATOR);
			}

			file.close();

		} catch (Exception ie) {
			ie.getMessage();
		}
	}
	
	/**
	 * Get the log chat
	 * @return the log chat
	 */
	public String getLogChat(){
		String log = "";
		for (String daVez : msgs) {
			log += daVez + LINE_SEPARATOR;
		}
		return log;
	}
}
